import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  // 一级路由
  { path: '/detail/:id', component: () => import('@/views/Detail.vue') },
  { path: '/login', component: () => import('@/views/Login.vue') },
  { path: '/register', component: () => import('@/views/Register.vue') },
  {
    path: '/',
    component: () => import('@/views/Home.vue'),
    children: [
      { path: 'article', component: () => import('@/views/Layout/Article.vue') },
      { path: 'collect', component: () => import('@/views/Layout/Collect.vue') },
      { path: 'like', component: () => import('@/views/Layout/Like.vue') },
      { path: 'user', component: () => import('@/views/Layout/User.vue') }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 这里要添加全局导航守卫  只能在床router之后 导出router之前加  很容易理解
router.beforeEach((to, from, next) => {
  // 如果是登录和注册页 则直接放行
  if (to.path === '/login' || to.path === '/register') {
    next()
  } else {
    // 其他页面 : 列表页, 收藏页, 用户页, 喜欢页  判断是否有token 有则通过 无则跳转到登录
    if (localStorage.getItem('mobile-token')) { // 这里只能判断有无token  那如果token错误了呢  不就放行了吗  所以需要响应拦截器
      next()
    } else {
      next('/login')
    }
  }
})

export default router
